﻿
using System;
using System.Net.Sockets; 
using System.Net; 
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace n_ESP8266
{
public static class ESP8266
{
	public delegate void D_SendByte( byte b );
	public static D_SendByte d_SendByte;
	
	static TcpClient tcpClient;//声明
    static NetworkStream networkStream;//网络流
	
    static byte[] ReadBuffer;
	
	static byte[] NetBuffer;
	static int SendLen;
	static int NetBufferLen;
	
	static bool NeedSend;
	static bool Connected;
	
	static Thread t;
	
	public static string Result;
	
	static string Web;
	static int Port;
	
	static int CMD;
	const int CMD_NONE = 0;
	const int CMD_CreatTCP = 1;
	
	
	//初始化
	public static void Init()
	{
		ReadBuffer = new byte[ 500 ];
		
		NetBuffer = new byte[ 500 ];
		NetBufferLen = 0;
		
		Connected = false;
		
		t = new Thread( new ThreadStart(ThreadProc) );
		OpenSim();
	}
	
	//结束
	public static void MyClose()
	{
		try {
		if( t != null && t.IsAlive ) {
			t.Abort();
			t.Join();
			
			//MessageBox.Show( "已结束socket调试线程" );
		}
		}
		catch(Exception e) {
			MessageBox.Show( e.ToString() );
		}
		if( tcpClient != null && tcpClient.Connected ) {
			tcpClient.Close();
		}
	}
	
	//开启仿真模拟
	public static void OpenSim()
	{
		t.Start();
	}
	
	//关闭仿真模拟
	public static void CloseSim()
	{
		t.Suspend();
		CloseTCP();
	}
	
	//----------------------------------------------------------------
	
	//创建TCP连接
	public static void CreatTCP( string web, int port )
	{
		Web = web;
		Port = port;
		
		CMD = CMD_CreatTCP;
	}
	
	//关闭TCP连接
	public static void CloseTCP()
	{
		if( tcpClient != null && tcpClient.Connected ) {
			tcpClient.Close();
		}
	}
	
	//用户发送数据到云平台
	public static void SentString( string ss )
	{
		byte[] byteArray = System.Text.Encoding.Default.GetBytes ( ss );
		for( int i = 0; i < byteArray.Length; ++i ) {
			NetBuffer[i] = byteArray[i];
		}
		SendLen = byteArray.Length;
		
		NeedSend = true;
	}
	
	//仿真时系统添加数据到云平台
	public static void AddByte( byte b )
	{
		NetBuffer[NetBufferLen] = b;
		NetBufferLen++;
		
		if( NetBufferLen >= 2 ) {
			if( NetBuffer[NetBufferLen - 2] == '\r' && NetBuffer[NetBufferLen - 1] == '\n' ) {
				
				string haha = "";
				for( int i = 0; i < NetBufferLen; ++i ) {
					haha += ((char)NetBuffer[i]).ToString();
				}
				
				//这里是AT指令
				if( NetBuffer[0] == 'A' ) {
					
					//MessageBox.Show( "A" + haha );
					
					if( haha.StartsWith( "AT+CIPSTART=" ) ) {
						CreatTCP( "www.bigiot.net", 8181 );
						
						//MessageBox.Show( "TCP" );
					}
				}
				else {
					
					//MessageBox.Show( "T" + haha );
					
					SendLen = NetBufferLen;
					NeedSend = true;
				}
				NetBufferLen = 0;
			}
		}
	}
	
	//----------------------------------------------------------------
	
	//执行线程 - 数据收发
	static void ThreadProc()
	{
		try {
		
		while( true ) {
			
			//判断是否需要创建套接字
			if( CMD == CMD_CreatTCP ) {
				CMD = CMD_NONE;
				
				//if( tcpClient == null || !tcpClient.Connected ) {
					
					tcpClient = new TcpClient( Web, Port );
					
					if( tcpClient != null ) {
						networkStream = tcpClient.GetStream();//得到网络流
						Connected = true;
						
						//MessageBox.Show( "TCPOK" );
					}
					else {
						Connected = false;
						MessageBox.Show( "连接失败!" );
					}
				//}
			}
			
			//判断是否有需要发送的数据
			if( Connected && NeedSend ) {
				
				try {
					networkStream.Write( NetBuffer, 0, SendLen );
				}
				catch ( Exception e ) {
					MessageBox.Show( "写入失败!" );
				}
				
				NeedSend = false;
			}
			//判断是否有需要接收的数据
			if( Connected && networkStream.DataAvailable ) {
				
				byte b = (byte)networkStream.ReadByte();
				
				if( d_SendByte != null ) {
					d_SendByte( b );
				}
				
				string rcMsg = ((char)b).ToString();
				
				if( rcMsg != null ) {
					Result += rcMsg;
				}
			}
		}
		} catch (Exception e) {
			MessageBox.Show( e.ToString() );
		}
	}
}
}
